package com.zking.secutity;

import com.zking.entity.Seller;
import com.zking.service.hcy.SellerService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class MyShiroRealm extends AuthorizingRealm {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

    @Autowired
    private SellerService sellerService;
    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     *
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        logger.info("---------------- 执行 Shiro 凭证认证 ----------------------");
        //用户输入的账号密码信息
        String principal = (String) authcToken.getPrincipal();
        //缺数据库的账号和密码
        //通过账号查询对应用户信息
        Seller seller = sellerService.querySellerBySellerId(principal);
        if (seller != null) {
            // 用户为禁用状态
            if (Integer.parseInt(seller.getStatus())!= 1) {
                throw new DisabledAccountException();
            }
            ByteSource salt = ByteSource.Util.bytes(seller.getMobile());
            SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(
                    seller,
                    seller.getPassword(),
                    salt,
                    getName());
            logger.info("---------------- 执行 Shiro 凭证认证成功 ------------------");
            return sai;
        }
        throw new UnknownAccountException();
    }


    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("---------------- 执行 Shiro 权限获取 ---------------------");
//        Object principal = principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        if (principal instanceof Seller) {
//            Seller seller = (Seller) principal;
//            List<String> roles = sellerService.queryRolesNameByUser(user);
//            info.addRoles(roles);
//            Set<String> authority = userService.queryAuthority(user);
//            //将权限告诉shiro
//            info.addStringPermissions(authority);
//        }
//        logger.info("---- 获取到以下权限 ----");
//        logger.info(info.getStringPermissions().toString());
//        logger.info(info.getRoles().toString());
//        logger.info("---------------- Shiro 权限获取成功 ----------------------");
//        return info;
        info.addStringPermission("/usersPage");
        return info;
    }

}
